<?php

require_once 'libs/P.php';

class GameController extends BaseController
{

    var $user_id;
    var $user_name;
    var $password;

    function init()
    {
        //get user info from sesssion
        $this->_bw_money = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_bw_money')
                ->order('money asc')
                ->queryAll();
        //get userinfo

        $this->user_id = Yii::app()->getSession()->get('user_id', '1');

      //  $this->user_name = 'Phu';
    }

    /**
     * Declares class-based actions.
     */
    public function actions()
    {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('blackorwhite','timbom', 'bomb','showlogs','datbom','index'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform
                'actions' => array('createbomb','huybom','bomcuatoi','bomtoigo','xacnhan', 'choilode', 'removebomb', 'chat',  'play', 'luckytrain', 'betbw'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex()
    {
        // using the default layout 'protected/views/layouts/main.php'
        $data = array();
        $this->render('index', $data);
    }
    
    public function actionShowLogs()
    {
    	//play logs data
    	$allplaylogs = Yii::app()->db->createCommand()
    	->select('*')
    	->from('ld_play_logs')
    	->limit(80, 0)
    	->order('id desc')
    	->queryAll();
    	$data['play_logs'] = $allplaylogs;
    	//chat data
    	$data['html_chat'] = $this->getChatData();
    	$this->renderPartial('show_logs',$data);    	
    	//exit('aaaaaaaaa');
    }
    
    public function actionHuybom()
    {
    	$bomb = Bomb::model()->find('id=:id',array(':id'=>$_POST['bomid']));
    	$hosterid=$bomb->user_set_id;
    	$user = User::model()->find('user_id = :user_id', array(':user_id' => $hosterid));
    	$bomb->status=2;
      	$user->lr_money=$user->lr_money+$bomb->money;
      	$user->save();
    	$bomb->save();
    }
    
    public function actionDatbom()
    {
    	$this->renderPartial('datbom');
    }
    
    public function actionbomtoigo()
    {
    	$page= isset($_GET['page']) ? $_GET['page']:1;
    	/*$mybomb_remove = Yii::app()->db->createCommand()
    	->select('*')
    	->from('ld_bomb')
    	->where('user_remove_id=:id2', array(':id2' => $this->user_id))
    	->queryAll();*/
    	$mybomb_remove = Yii::app()->db->
    	createCommand("SELECT a.*,b.user_name as user_set_name
    			FROM ld_bomb a left join ld_user b on a.user_set_id=b.user_id
    			WHERE status <> 2 and a.user_remove_id=".$this->user_id."
    			 order by a.id desc LIMIT
    			".(($page-1)*10).",10"
    			)
    	->queryall();
    	
    	$num=Yii::app()->db->createCommand("select count(*) from
    			(SELECT a.*,b.user_name as user_remove_name
    			FROM ld_bomb a left join ld_user b on a.user_remove_id=b.user_id
    			WHERE status <> 2 and a.user_remove_id=".$this->user_id."
    			  order by a.id desc
    	) as t")->queryScalar();
    	echo 'Số bom : '.$num;
    	$data['maxpage']=($num-$num%10)/10+1;
    	    	
    	$data['mybomb_remove'] = $mybomb_remove;
    	$this->renderPartial('bomtoigo',$data);	
    }
    
    public function actiontimbom()
    {
    	
    
    		
    	$allbomb = Yii::app()->db->
    	createCommand("SELECT a.*,b.user_name as user_set_name
    			FROM ld_bomb a left join ld_user b on a.user_set_id=b.user_id
    			WHERE status =0 and a.user_set_id<>".$this->user_id)
    			->queryall();    	
      /* $allbomb = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_bomb')
                ->where('status=:stt and user_set_id<>:uid', array(':stt' => '0', ':uid'=>$this->user_id))
                ->queryAll();*/
        $data['allbomb'] = $allbomb;
        
    	$this->renderPartial('timbom',$data);
    }
    
    public function actionbomcuatoi()
    {
    	$page= isset($_GET['page']) ? $_GET['page']:1;
    	$mybomb = Yii::app()->db->
    	createCommand(
    			"SELECT a.*,b.user_name as user_remove_name
FROM ld_bomb a left join ld_user b on a.user_remove_id=b.user_id
WHERE status <> 2 and a.user_set_id=".$this->user_id." order by a.id desc LIMIT
    			".(($page-1)*10).",10"
    			)
    	//->select('a.*')
    	//->from('ld_bomb a left join ld_user b on a.user_remove_id=b.user_id')
    	//->where('status <> 2 and a.user_set_id=:id', array(':id' => $this->user_id))
    	->queryAll();
    	
    	$num=Yii::app()->db->createCommand("select count(*) from 
(SELECT a.*,b.user_name as user_remove_name
FROM ld_bomb a left join ld_user b on a.user_remove_id=b.user_id
WHERE status <> 2 and a.user_set_id=".$this->user_id."  order by a.id desc 
) as t")->queryScalar();
    	
    	echo 'Số bom :'.$num;
    	$data['maxpage']=($num-$num%10)/10+1;
    	$data['mybomb'] = $mybomb;
    	$this->renderPartial('bomcuatoi',$data);
    }

    //cat day bomb
    public function actionremovebomb()
    {
    	//exit('aaaaaaaaaaaaaaaaa'.$_POST['string_color'].'----'.$_POST['game_id']);
        $this->init();
        if (isset($_POST['game_id']) && isset($_POST['string_color']))
        {
        	if (($_POST['string_color']<>1)&&($_POST['string_color']<>-1))
        	{
        		Yii::app()->db->createcommand("UPDATE ld_user SET banned=1 where user_id=".Yii::app()->user->id)->query();
        		exit('Bạn có hành vi hack website, tài khoản của bạn đã bị banned');
        	}
        	
            $string_color = $_POST['string_color'];
            $game_id = $_POST['game_id'];

            //get game info
            $gamebomb = array();
           
            $gamebomb = Yii::app()->db->createCommand()
                    ->select('b.user_name,a.*')
                    ->from('ld_bomb a')
                    ->join('ld_user b', 'a.user_set_id = b.user_id')
                    ->where('status=:stt and id=:game_id', array(':stt' => '0', ':game_id' => $game_id))
                    ->queryRow();
         	if (!$gamebomb){
         		exit('Rat tiec, bom này vừa mới có người gỡ xong');
         	}
            //user play
            $cur_user = Yii::app()->db->createCommand()
                    ->select('*')
                    ->from('ld_user')
                    ->where('user_id=:id1', array(':id1' => $this->user_id))
                    ->queryRow();
            
            $other_user = Yii::app()->db->createCommand()
            ->select('*')
            ->from('ld_user')
            ->where('user_id=:id1', array(':id1' => $gamebomb['user_set_id']))
            ->queryRow();            
//exit($cur_user["lr_money"].'  '.$gamebomb['money']);
            //check is enoug money
           // print_r('XONG'.$gamebomb['color'].'----'.$string_color.'======'.$_POST['string_color']);
            if ($cur_user['lr_money'] >= $gamebomb['money'])
            {
            	// Du thang hay thua thi tien cuoc de chia hoa hong cua 2 thang deu fai tang
            	if($gamebomb['money']>=5 && $gamebomb['money']<=10)
            	{
 // ko chia cho nguoi gioi thieu nua
    /*        		$newtotalspent=$cur_user['total_spent']+$gamebomb['money'];
            		$newlastspent=$cur_user['last_section_spent']+$gamebomb['money'];
            		
            		Yii::app()->db->createCommand()->update('ld_user', array('total_spent' => $newtotalspent,
            				'last_section_spent'=>$newlastspent
            		), 'user_id='.$this->user_id);
            		
            		$newtotalspent=$other_user['total_spent']+$gamebomb['money'];
            		$newlastspent=$other_user['last_section_spent']+$gamebomb['money'];
            		
            		Yii::app()->db->createCommand()->update('ld_user', array('total_spent' => $newtotalspent,
            				'last_section_spent'=>$newlastspent
            		), 'user_id='.$other_user['user_id']);
      */      	
            	}
            	            	
                if ($gamebomb['color'] == $string_color)
                {
               		//echo 'dung roi ma';
                    //win - set lai status game

                   //add point - subtract point for user
                    //get current userinfo

                    $cur_point_user = $cur_user['lr_money'];
                    $moneygetwin = 0;

      // chinh sach 1 gia cho tro dat bom
                   if($gamebomb['money']>=0.5 && $gamebomb['money']<2)
                   {
                   //		$cur_point_user += ($gamebomb['money']-0.05);
                  //     $moneygetwin = ($gamebomb['money']-0.05);
                   }
                   if($gamebomb['money']>=2 && $gamebomb['money']<5)
                   {
                  // 		$cur_point_user += ($gamebomb['money']-0.1);
                   //    $moneygetwin = ($gamebomb['money']-0.1);
                   }
                   if($gamebomb['money']>=5 && $gamebomb['money']<=10)
                   {
                   		//	$cur_point_user += (($gamebomb['money']*90)/100);
                       //  $moneygetwin = (($gamebomb['money']*90)/100);
                   }
                   $cur_point_user+=$gamebomb['money'];
                   $moneygetwin=$gamebomb['money'];
                   $columns = array();
                   $columns['status'] = 1; // bom duoc go
                   $columns['date_remove'] = date('Y-d:m H:i:s',strtotime("+14 hours"));
                   $columns['user_remove_id'] = Yii::app()->user->id;
                   $columns['win_money']=$moneygetwin;
                   Yii::app()->db->createCommand()->update('ld_bomb', $columns, 'id='.$game_id);
                   
                   // $cur_point_user += $gamebomb['money'];
                    //update
                    Yii::app()->db->createCommand()->update('ld_user', array('lr_money' => $cur_point_user), 'user_id='.$this->user_id);

                    //ld_remove_bomb
                   /* $ld_remove_bomb = array();
                    $ld_remove_bomb['make_bomb_id'] = $gamebomb['id'];
                    $ld_remove_bomb['remove_bomb_user_id'] = $this->user_id;
                    $ld_remove_bomb['choosen'] = $string_color;
                    Yii::app()->db->createCommand()->insert('ld_remove_bomb', $ld_remove_bomb);
                    */
                    echo 'Xin chúc mừng !!! Bạn đã phá được bom và nhận được '.$moneygetwin.'$';
                    
                    
                    //insert log
                    $win = array();
                    $win['content'] = date("Y-m-d H:i:s",strtotime("+14 hours")).'  -- <b>' .Yii::app()->user->name. '</b> đã gỡ thành công bom của <b>'.$gamebomb['user_name'] .'</b> và đã kiếm được ' . $moneygetwin."$";
                    $win['status'] = 1;
                    Yii::app()->db->createCommand()->insert('ld_play_logs', $win);
                }
                else
                {

                    //insert log
                    $log = array();
                    $log['content'] = date("Y-m-d H:i:s",strtotime("+14 hours")).'  -- <b>' . Yii::app()->user->name . '</b> bị nổ banh xác vì bom của <b>'.$gamebomb['user_name'].'</b> và đánh rơi ' . $gamebomb['money'].'$';
                    $log['status'] = 0;
                    Yii::app()->db->createCommand()->insert('ld_play_logs', $log);
                    
                    
                    //tinh diem cho doi thu
                    $cur_point_user = $gamebomb['money'];
                    //chinh sach 1 gia 4%
                    
                    
                    if($gamebomb['money']>=0.5 && $gamebomb['money']<2)
                    {
           //         	$cur_point_user += $gamebomb['money']-0.05;
                    }
                    if($gamebomb['money']>=2 && $gamebomb['money']<5)
                    {
                  //  	$cur_point_user += $gamebomb['money']-0.1;
                    }
                    if($gamebomb['money']>=5 && $gamebomb['money']<=10)
                    {
                  //  	$cur_point_user += ($gamebomb['money']*90)/100;
                    }
                    $cur_point_user+=$gamebomb['money'];
                    //lose - set lai status game
                    $columns = array();
                    $columns['status'] = -1;// bom no?
                    $columns['date_remove'] = date('Y-d-m H:i:s',strtotime("+14 hours"));
                    $columns['user_remove_id'] = Yii::app()->user->id;
                    $columns['win_money'] = $cur_point_user-$gamebomb['money'];
                    $columns['color']=$string_color*(-1);
                    //echo $columns['color'];
                    //var_dump($columns);
                    Yii::app()->db->createCommand()->update('ld_bomb', $columns, 'id='.$game_id);
                    
                    $host_user=Yii::app()->db->createCommand()
                    ->select('*')
                    ->from('ld_user')
                    ->where('user_id=:id1', array(':id1' => $gamebomb['user_set_id']))
                    ->queryRow();
                 //   echo ' so tien thang host hien gio '.$host_user['lr_money'];
                 //   echo ' so tien no thang duoc nho dat bom '.$cur_point_user;
                    $host_money=$host_user['lr_money']+$cur_point_user;
                 //   echo ' so tien update vao db : '.$host_money;

                        
                    // $cur_point_user += $gamebomb['money'];
                    //update
                    Yii::app()->db->createCommand()->update('ld_user', array('lr_money' => $host_money), 'user_id=' . $gamebomb['user_set_id']);
                    //tru tien thang dang choi
                    $change=array();
                    $require_money=$gamebomb['money'];
                    if ($cur_user['lr_khuyenmai']>=$require_money)
                    {
                    	$change['lr_khuyenmai']=$cur_user['lr_khuyenmai']-$require_money;
                    }else
                    {
                    	$change['lr_khuyenmai']=0;
                    	$require_money-=$cur_user['lr_khuyenmai'];
                    	$change['lr_money']=$cur_user['lr_money']-$require_money;
                    }
                    
                    Yii::app()->db->createCommand()->update('ld_user',
                    		 $change,
                    		 'user_id=' . $this->user_id);
                    
                    //ld_remove_bomb
                   /* $ld_remove_bomb = array();
                    $ld_remove_bomb['make_bomb_id'] = $gamebomb['id'];
                    $ld_remove_bomb['remove_bomb_user_id'] = $this->user_id;
                    $ld_remove_bomb['choosen'] = $string_color;
                    Yii::app()->db->createCommand()->insert('ld_remove_bomb', $ld_remove_bomb);
                    */
                    //output error
                    echo 'Chia buồn. Bạn đã bị nổ banh xác và đánh rơi '.$gamebomb['money'].' $';
                }
            }
            else
            {
                //khong Ä‘á»§ tiá»�n
                echo 'Bạn không có đủ '.$gamebomb['money'].'$ để thử gỡ bom này';
            }
        }
    }

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    
    public function actionCreateBomb()
    {
    	//dat bomb
    	if (isset($_POST['makebomb']) && isset($_POST['day']) && isset($_POST['bet_money']))
    	{
    		//check xem co tien ko da
    		$cuUser = Yii::app()->db->createCommand()
    		->select('*')
    		->from('ld_user')
    		->where('user_id=:uid', array(':uid'=>$this->user_id))
    		->queryRow();
    		//pham vi dat tien 0.5-10
    		if(!is_numeric($_POST['bet_money']) || $_POST['bet_money'] >10)
    		{
    			$data['error'] = 'Số tiền phải là số và nhỏ hơn 10$, nếu là dầu thập phân thì cách nhau bởi dấu chấm không phải dấu phẩy ';
    		}else{
    			if($cuUser['lr_money']+$cuUser['lr_khuyenmai'] < $_POST['bet_money'])
    			{
    				$data['error'] = 'Bạn không đủ tiền để đặt bom, vui lòng nạp thêm tiền hoặc chọn mức đánh thấp hơn :) ';
    			}else
    			{
    				//insert make bomb table
    				/*$makebomb = array();
    				 $makebomb['user_id'] = $this->user_id;
    				$makebomb['string_color'] = $_POST['day'];
    				$makebomb['status'] = 0;
    				$makebomb['date_start'] = date('Y:m:d H:i:s');
    				$makebomb['money'] = $_POST['bet_money'];
    				//insert
    				Yii::app()->db->createCommand()->insert('ld_make_bomb', $makebomb);
    				*/
    				$newbomb = array();
    				$newbomb['color'] = $_POST['day'];
    				$newbomb['user_set_id'] = $this->user_id;
    				$newbomb['date_set']= date('Y:m:d H:i:s');
    				$newbomb['status'] = 0;
    				$newbomb['money'] = $_POST['bet_money'];
    				//insert
    				Yii::app()->db->createCommand()->insert('ld_bomb',$newbomb);
    				 
    				$data['success'] = 'Đặt bom thành công. Chúc bạn gặp nhiều may mắn :)';
    	
    				//tru tien cua no di
    				 
    				$user = array();
    				$requiredMoney= $_POST['bet_money'];
    				if ($cuUser['lr_khuyenmai'] >= $requiredMoney)
    				{
    					$user['lr_khuyenmai']=$cuUser['lr_khuyenmai']-$requiredMoney;
    				}else
    				{
    					$requiredMoney-=$cuUser['lr_khuyenmai'];
    					$user['lr_khuyenmai']=0;
    					$user['lr_money'] = $cuUser['lr_money'] - $requiredMoney;
    				}
    				
    				//$user['lr_money']  = $cuUser['lr_money'] - $_POST['bet_money'];
    				//$user['total_spent']+=$_POST['bet_money'];
    				//$user['last_section_spent']+=$_POST['bet_money'];
    				Yii::app()->db->createCommand()
    				->update('ld_user', $user, 'user_id=' . $this->user_id);
    				 
    				$log = array();
    				$log['content'] = date("
    						Y-m-d H:i:s",strtotime("+14 hours")).'  -- <b>' .Yii::app()->user->name. '</b> vừa mới đặt bom trị giá $'.$_POST['bet_money'];
    				$log['status'] = 1;
    				Yii::app()->db->createCommand()->insert('ld_play_logs', $log);
    			}
    		}
    		 
    	}
    	else
    	{
    		if (isset($_POST['makebomb']) && (!isset($_POST['string_color']) || !isset($_POST['bet_money'])))
    		{
    			$data['error'] = 'Mời bạn nhập số tiền và chọn dây';
    		}
    	}
    	$this->render('createbomb',$data);
    }
    
    public function actionBomb()
    {
        // renders the view file 'protected/views/site/index.php'
        // using the default layout 'protected/views/layouts/main.php'
        //command
        $this->init();
        $user_id = $this->user_id;

        //load data
        $rule = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_setting')
                ->where('variable=:v', array(':v' => 'bomb_rule_text'))
                ->queryRow();
        $data['rule'] = $rule;

        

        
        //huy bomb
      /*  if(isset($_GET['huy']) && $_GET['huy'] =='yes')
        {
        	//check xem co tien ko da
        	$cuUser = Yii::app()->db->createCommand()
        	->select('*')
        	->from('ld_user')
        	->where('user_id=:uid', array(':uid'=>$this->user_id))
        	->queryRow();
        	$idhuy = $_GET['id'];
        	//set status is huy
        	$huy = array();
        	$huy['status'] = 2;
        	Yii::app()->db->createCommand()
        				->update('ld_make_bomb', $huy, 'user_id=' . $this->user_id . ' and id=' . $idhuy);
        	//tra lai tien cho user
        	$user = array();
        	$user['lr_money']  = $cuUser['lr_money'] - $_POST['bet_money'];
        	Yii::app()->db->createCommand()
        	->update('ld_user', $user, 'user_id=' . $this->user_id);        	
        }*/
        
        //get all bomb cua toi
       /* $mybomb = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_make_bomb mb')
                ->leftJoin('ld_remove_bomb rb', 'rb.make_bomb_id = mb.id')
                ->leftJoin('ld_user u', 'u.user_id = rb.remove_bomb_user_id')
                ->where('mb.user_id=:id', array(':id' => $user_id))
                ->queryAll();*/
        
        $mybomb = Yii::app()->db->createCommand()
			        ->select('*')
			        ->from('ld_bomb')
			        ->where('status <> 2 and user_set_id=:id', array(':id' => $user_id))
			        ->queryAll();
        
        $data['mybomb'] = $mybomb;

        //all bomb toi go
        $mybomb_remove = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_bomb')
                ->where('user_remove_id=:id2', array(':id2' => $user_id))
                ->queryAll();
        $data['mybomb_remove'] = $mybomb_remove;

        //get all bomb cho` de go
        $allbomb = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_bomb')
                ->where('status=:stt and user_set_id<>:uid', array(':stt' => '0', ':uid'=>$this->user_id))
                ->queryAll();
        $data['allbomb'] = $allbomb;


        $this->render('bomb', $data);
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError()
    {
        if ($error = Yii::app()->errorHandler->error)
        {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionChat()
    {
        if (isset($_POST['act']) && $_POST['act'] == 'chataction')
        {
            $command = Yii::app()->db->createCommand();
            $data = array();
            $data['user_id'] = $this->user_id;
            $data['comment'] = $_POST['txt'];
            $data['date'] = date("Y-m-d H:i:s",strtotime('+14 hours'));
            //insert database
            $command->insert('ld_chat_bomb', $data);
            //update chat html
            echo $this->getChatData();
        }
    }

    /*
     * Get chat data from ld_chat_bomb
     */

    public function getChatData()
    {
        $chat = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_chat_bomb cb')
                ->join('ld_user u', 'u.user_id=cb.user_id')
                ->order('id desc')
                ->queryAll();

        $html_chat = '';

        foreach ($chat as $c)
        {
            $html_chat .= '<b>- '.$c['user_name'].' </b><i style="font-size:10px;color:red">('.$c['date'].')</i>: '.$c['comment'].'<br/>';
        }
        return $html_chat;
    }

    //game blackorwhite
    public function actionBlackorWhite()
    {
    	/*$n = rand(10e16, 10e20);
    	echo base_convert($n, 10, 36);
    	echo chr(3).'dcm';
    	$str="";
    	for($i=0;$i<=4;$i++){
    	$num=mt_rand(10000,99999);
		$str.="$num";
    	}
		echo $str;*/
       /* if (mt_rand(0,99999)%2==0){
    		$str='WHITE-';
    	}else
    	{
    		$str='BLACK-';
    	}
    	for ($i=0;$i<20;$i++)
    	{
    		$str.=chr(97 + (mt_rand(0, 99999)%26));
    	}
    	
		$hash=md5($str);*/
    	//echo $str.'<br/>'.$hash;
    	//echo base_convert(mt_rand(10000,99999),10,36);
        $this->init();
        $data = array();
        //load data
        $rule = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_setting')
                ->where('variable=:v', array(':v' => 'blackorwhite_rule_text'))
                ->queryRow();
        $data['rule'] = $rule;
        //asign money
        $data['bw_money'] = $this->_bw_money;
        $this->render('blackorwhite', $data);
        
    }

    var $_result; //result 
    var $_bw_money; //array of money alow to play

    //http post
    //blackorwhite bet

    public function actionBetbw()
    {
    	$this->init();
    
        //check xem dang nhap chua
        $is_login = true;
        if ($is_login == false)
        {
            echo '<h2>Có lỗi</h2><br>Bạn cần đăng nhập mới có thể chơi trò này';
        }
        else
        {
            //check lr of user - can play game with that bet money or not
            $user = Yii::app()->db->createCommand()
            					->select('*')
            					->from('ld_user')
            					->where('user_id=:id and active=:status', array(':id' => $this->user_id, ':status' => '1'))
            					->queryRow();
            //var_dump($user);
            $user_lr = $user['lr_money'];
            $bet_money = $_POST['money'];
            if ($user_lr < $bet_money)
            {
                //can't play
                echo 'lowpoint';
            }
            else
            {
                //can play this game
                //get result from string 1: black 0:white
                //this will be 70 percent can be win
                
                $listscore_black = explode(' ', '0 1 0 1 0 1 1 0 0 1');
                $listscore_white = explode(' ', '1 0 0 0 1 0 1 1 0 1');
                
                if ($bet_money>0.5){
                	$listscore_black[1]=0;
                	$listscore_white[1]=1;
                }
                
                if ($bet_money>5){
                	$listscore_black[5]=0;
                	$listscore_white[5]=1;
                }                

                if (isset($_POST['chose']))
                {
                    //if user chose black
                    if ($_POST['chose'] == 'black')
                    {
                        //user list $listscore_black
                        $random_num_black = mt_rand(0, 9);
                        $this->_result = $listscore_black[$random_num_black];
                    }
                    //if user chose white
                    if ($_POST['chose'] == 'white')
                    {
                        //user list $listscore_black
                        $random_num_white = mt_rand(0, 9);
                        $this->_result = $listscore_white[$random_num_white];
                    }
                }

                //return to user win or lose
                switch ($this->_result)
                {
                    case '1':
                        echo 'black';
                        $this->_result = 'black';
                        break;
                    case '0':
                        echo 'white';
                        $this->_result = 'white';
                    default:
                        ;
                        break;
                }

                //check the result:
                //- win: add lr to user
                //- lose: subtract lr
                //data: - user_id - chose - money - result
                $data['user_id'] = $this->user_id;
                $data['chose'] = $_POST['chose'];
                $data['result'] = $this->_result;
                $data['money'] = $bet_money;
                $data['playdate'] = date("Y-m-d H:i:s",strtotime("+14 hours"));
                $insert_bw_play_logs = Yii::app()->db->createCommand()->insert('ld_bw_logs', $data);

                //check win or lose and save to db
                if ($this->_result == $_POST['chose'])
                {
                    $user_liberty = $user['lr_money'];
                    $user_liberty += $bet_money*0.9;
            	$log = array();
            	$log['content'] = date("Y-m-d H:i:s",strtotime("+14 hours")).'  -- <b>' .Yii::app()->user->name. '</b> vừa mới chơi game black or white và lãi '.$bet_money*0.9.'$';
            	$log['status'] = 1;
            	Yii::app()->db->createCommand()->insert('ld_play_logs', $log);
                }
                if ($this->_result != $_POST['chose'])
                {
                    $user_liberty = $user['lr_money'];
                    $user_liberty -= $bet_money;
                    $log = array();
                    $log['content'] = date("Y-m-d H:i:s",strtotime("+14 hours")).'  -- <b>' .Yii::app()->user->name. '</b>  vừa mới chơi game black or white và thua '.$bet_money.'$';
                    $log['status'] = 1;
                    Yii::app()->db->createCommand()->insert('ld_play_logs', $log);                   
                }
                $datauser['lr_money'] = $user_liberty;
                //win or lose - add or subtract point
                Yii::app()->db->createCommand()->update('ld_user', $datauser, 'user_id='.$this->user_id);
            }
        }
    }

    //http post
    //blackorwhite bet
    public function actionPlay()
    {
        if ($_POST['type'] == 'loadinfo')
        {
            echo 'Phu | Nguyen';
        }

        if ($_POST['type'] == 'loadbwhis')
        {
            //show history of this user
            $this->init();
            $hist_play = array();
            $hist_play = Yii::app()->db->createCommand()
                    ->select('*')
                    ->from('ld_bw_logs')
                    ->where('user_id=:id', array(':id' => $this->user_id))
                    ->limit(10, 0)
                    ->order('playdate desc')
                    ->queryAll();

            foreach ($hist_play as $hp)
            {
                if ($hp['chose'] == $hp['result'])
                {
                	echo 'Bạn chọn <b>'.$hp['chose'].' </b> và cược <span style="color:red"><b>'.$hp['money'].'$</b></span>';
                    echo '. Kết quả là  <b>'.$hp['result'].'</b> -> bạn nhận được <span style="color:red"><b>'.$hp['money']*1.9.'$</b></span><br/>';
                }
                else
                {
                    if ($hp['chose'] != $hp['result'])
                    {
                    	echo 'Bạn chọn <b>'.$hp['chose'].' </b> và cược <span style="color:red"><b>'.$hp['money'].'$</b></span>';
                        echo '. Kết quả là  <b>'.$hp['result'].'</b> -> bạn nhận được <span style="color:red"><b>0$</b></span><br/>';
                    }
                }
            }
        }
    }

    //game luckytrain
    public function actionLuckyTrain()
    {
        $this->init();

        $data = array();
        //load data
        $rule = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_setting')
                ->where('variable=:v', array(':v' => 'luckytrain_rule_text'))
                ->queryRow();
        $data['rule'] = $rule;
        //load thong tin history
        $lucky_train_next = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_lucky_train lt')
                ->where('lt.status=:id2', array(':id2' => '0'))
                ->queryRow();
        //number user join
        $userjoin = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_lucky_train_logs ltl')
                ->where('ltl.game_id=:gameid2', array(':gameid2' => $lucky_train_next['id']))
                ->order('position asc')
                ->queryAll();
        
        //join
        if (isset($_POST['buyit']))
        {
        	
        	//get current user info
        	$cur_USer = Yii::app()->db->createCommand()
			        	->select('*')
			        	->from('ld_user')
			        	->where('user_id=:uid', array(':uid'=>$this->user_id))
			        	->queryRow();
        	//check xem du tien choi ko
        	if($cur_USer['lr_money']>=1)
        	{
        		//tru tien choi 1$
        		Yii::app()->db->createCommand()->update('ld_user', array('lr_money' => $cur_USer['lr_money']-1), 'user_id='. $this->user_id);
        		//get max player can play
        		$ld_setting = P::getAllRows('ld_setting');
        		$maxpalyer = 0;
        		foreach ($ld_setting as $st)
        		{
        			if ($st['variable'] == 'lucky_train_num_play')
        			{
        				$maxpalyer = $st['value'];
        			}
        		}
        		if (count($userjoin)+1 < $maxpalyer)
        		{
        			//insert to database
        			$user = array();
        			$user['user_id'] = $this->user_id;
        			$user['playdate'] = date('Y:m:d H:i:s');
        			if (count($userjoin) == 0)
        			{
        				$user['position'] = 1;
        			}
        			else
        			{
        				$user['position'] = $userjoin[count($userjoin) - 1]['position'] + 1;
        			}
        			$user['game_id'] = $lucky_train_next['id'];
        			Yii::app()->db->createCommand()->insert('ld_lucky_train_logs', $user);
        		
        			//if is winner - set user_id int ld_lucky_train
        			if ($lucky_train_next['result_num'] == $user['position'])
        			{
        				Yii::app()->db->createCommand()->update('ld_lucky_train', array('user_id' => $this->user_id), 'id='.$lucky_train_next['id']);
        				//cong diem cho user
        		
        				Yii::app()->db->createCommand()->update('ld_user', array('lr_money' => $cur_USer['lr_money']+9), 'user_id='. $this->user_id);
        			}
        		}else
        		{
        			//5 user
        			if(count($userjoin)+1 == $maxpalyer)
        			{
        				//cap nhat user_id thang game
        				Yii::app()->db->createCommand()->update('ld_lucky_train', array('status' => '1', 'enddate'=>date('Y:m:d H:i:s')), 'id='.$lucky_train_next['id']);
        		
        				//create new game
        				//random num next
        				$num_next = rand(1, 10);
        				$random_string = P::generateRandomString(8);
        				$newluckytrain = array();
        				$newluckytrain['result_num'] = $num_next;
        				$newluckytrain['random_string'] = $random_string;
        				$newluckytrain['startdate'] = date('Y:m:d H:i:s');
        				$newluckytrain['status'] = 0;
        		
        				Yii::app()->db->createCommand()->insert('ld_lucky_train', $newluckytrain);
        			}
        		}
        	
        	}else
        	{
        		$data['error'] = 'Báº¡n khÃ´ng Ä‘á»§ 1$ Ä‘á»ƒ chÆ¡i, vui lÃ²ng náº¡p thÃªm';
        	}
        }

        $lucky_train_next = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_lucky_train lt')
                ->where('lt.status=:id2', array(':id2' => '0'))
                ->queryRow();

        //number user join
        $userjoin = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_lucky_train_logs ltl')
                ->where('ltl.game_id=:gameid2', array(':gameid2' => $lucky_train_next['id']))
                ->order('playdate asc')
                ->queryAll();
        $lucky_train_hist = Yii::app()->db->createCommand()
                ->select('*')
                ->from('ld_lucky_train lt')
                ->join('ld_user u', 'u.user_id = lt.user_id')
                ->where('lt.status=:id2', array(':id2' => '1'))
                ->queryAll();

        $data['lucky_train_hist'] = $lucky_train_hist;
        $data['lucky_train_next'] = $lucky_train_next;
        $data['number_join'] = count($userjoin);
        $this->render('luckytrain', $data);
    }

    public function actionChoiLoDe()
    {
        $now = date('H:i:s d-m-Y',strtotime("+14 hours"));
        $start = date('18:30:00 d-m-Y');
        $end = date('20:00:00 d-m-Y');
        if ($now >= $start && $now <= $end)
        {
            $this->render('khoagame');
            die ();
            return;
        }
        
        $choices = isset($_REQUEST['choices']) ? $_REQUEST['choices'] : array();
        $bet = (isset($_REQUEST['bet']) && is_numeric($_REQUEST['bet'])) ? $_REQUEST['bet'] : 0;
        $gameType = (isset($_REQUEST['type']) && $_REQUEST['type'] !== '') ? $_REQUEST['type'] : 0;

        $isValid = $this->validateGameLoDeInputs($choices, $bet, $gameType);
        if ($isValid)
        {
            $game = LoDeFactory::createGameLoDe($gameType);
            $game->setBet($bet);
            $game->setChoices($choices);
            $user = User::model()->find('user_id = :user_id', array(':user_id' => Yii::app()->user->id));
            $requiredMoney = $game->bet;//$game->calculateRequiredAmount();
            //$guareenty = $game->calculateGuareentyAmount();

            if ($requiredMoney > $user->lr_money+$user->lr_khuyenmai)
            {
                $depositURL = $this->createAbsoluteUrl('user/deposit');
                Yii::app()->user->setFlash('error', array("Bạn không đủ tiền để chơi. Bạn chỉ còn {$user->lr_money} $. Nhấp vào <a href='$depositURL'>Đây</a> để nạp thêm tiền"));
                $this->render('../site/index');
                return;
            }
            
            $user->total_spent += $requiredMoney;
            $user->last_section_spent += $requiredMoney;
                        
            if ($user->lr_khuyenmai >= $requiredMoney)
            {
            	$user->lr_khuyenmai -=$requiredMoney;
            }else 
            {
            	$requiredMoney-=$user->lr_khuyenmai;
            	$user->lr_khuyenmai=0;
            	$user->lr_money = $user->lr_money - $requiredMoney;
            }

            if ($user->save() && $game->saveDB())
            {
            	$log = array();
            	$log['content'] = date("Y-m-d H:i:s",strtotime("+14 hours")).'  -- <b>' .Yii::app()->user->name. '</b> vừa mới đánh lô đề ';
            	$log['status'] = 1;
            	Yii::app()->db->createCommand()->insert('ld_play_logs', $log);
                $this->render('thongbao');
            }
            else
            {
                Yii::app()->user->setFlash('error', array('Có lỗi xảy ra. Xin bạn vui lòng thử lại'));
                $this->render('../site/index');
            }
        }
        else
        {
            $this->render('../site/index');
        }
    }

    public function actionXacNhan()
    {
        $now = date('H:i:s d-m-Y');
        $start = date('4:30:00 d-m-Y');
        $end = date('6:00:00 d-m-Y');
        if ($now >= $start && $now <= $end)
        {
            $this->render('khoagame');
            return;
        }
        else
        {
            $choices = isset($_REQUEST['choices']) ? $_REQUEST['choices'] : array();
            $type = (isset($_REQUEST['type']) && $_REQUEST['type'] !== '') ? $_REQUEST['type'] : 0;
            $bet = (isset($_REQUEST['bet']) && is_numeric($_REQUEST['bet'])) ? $_REQUEST['bet'] : 0;
            if ($type<2 || $type>4){
            	$bet=$bet*count($choices);
            }
            $game = LoDeFactory::createGameLoDe($type);

            $this->render('xacnhan', array('gameName' => $game->getGameName(), 'choices' => $choices, 'bet' => $bet, 'type' => $type));

        }
    }

    private function validateGameLoDeInputs($choices, $bet, $gameType)
    {
        $error = array();

        if ($gameType == 0)
        {
            $error += array('Loại đề mà bạn đánh không hợpe ệ');
        }

        if ($bet <0.1)
        {
            $error += array('Số tiền cược phải lớn hơn hoặc bằng 0.1$');
        }

        if (count($choices) == 0)
        {
            $error += array('Bạn chưa chọn số');
        }

        foreach ($choices as $choice)
        {
            if ($choice === '')
            {
                $error += array('Số bạn chọn không hợp lệ');
            }
        }

        $game = LoDeFactory::createGameLoDe($gameType);
        if ($game==null)
        {
        	Yii::app()->user->setFlash('error', $error);
        	return FALSE;
        }
        $game->setBet($bet);

        $game->setChoices($choices);
        if (!$game->validateInputs())
        {
            $error += array('Các số chọn không hợpe lệ');
        }
        if (count($error) > 0)
        {
            Yii::app()->user->setFlash('error', $error);
            return FALSE;
        }

        return TRUE;
    }

}